import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useAccountStore = defineStore("account", () => {
  // 状态
  const accounts = ref([]);
  const currentAccountId = ref(null);

  // 获取当前账号
  const currentAccount = computed(() => {
    if (!currentAccountId.value) return null;
    return (
      accounts.value.find((acc) => acc.id === currentAccountId.value) || null
    );
  });

  // 添加账号
  function addAccount(account) {
    const id = Date.now().toString();
    const newAccount = {
      id,
      wxid: account.wxid || null,
      nickname: account.nickname || "未知用户",
      port: account.port || 8989,
      status: account.status || "offline", // offline, logging_in, online, error
      createdAt: new Date().toISOString(),
      ...account,
    };

    accounts.value.push(newAccount);
    saveToLocalStorage();

    return id;
  }

  // 更新账号
  function updateAccount(id, updates) {
    const index = accounts.value.findIndex((acc) => acc.id === id);
    if (index !== -1) {
      accounts.value[index] = {
        ...accounts.value[index],
        ...updates,
        updatedAt: new Date().toISOString(),
      };
      saveToLocalStorage();
      return true;
    }
    return false;
  }

  // 删除账号
  function removeAccount(id) {
    const index = accounts.value.findIndex((acc) => acc.id === id);
    if (index !== -1) {
      accounts.value.splice(index, 1);

      // 如果删除的是当前账号，则清空当前账号
      if (currentAccount.value && currentAccount.value.id === id) {
        currentAccount.value = null;
      }

      // 保存到本地存储
      saveToLocalStorage();
      return true;
    }
    return false;
  }

  // 设置当前账号
  function setCurrentAccount(id) {
    const account = accounts.value.find((acc) => acc.id === id);
    if (account) {
      currentAccountId.value = id;
      saveToLocalStorage();
      return true;
    }
    return false;
  }

  // 获取所有账号
  function getAllAccounts() {
    return accounts.value;
  }

  // 保存到本地存储
  function saveToLocalStorage() {
    try {
      localStorage.setItem("wx_accounts", JSON.stringify(accounts.value));
      localStorage.setItem("wx_current_account", currentAccountId.value);
    } catch (error) {
      console.error("保存账号数据失败:", error);
    }
  }

  // 从本地存储加载
  function loadFromLocalStorage() {
    try {
      const savedAccounts = localStorage.getItem("wx_accounts");
      const savedCurrentAccount = localStorage.getItem("wx_current_account");

      if (savedAccounts) {
        accounts.value = JSON.parse(savedAccounts);
      }

      if (savedCurrentAccount) {
        currentAccountId.value = savedCurrentAccount;
      }
    } catch (error) {
      console.error("加载账号数据失败:", error);
    }
  }

  // 初始化
  function initialize() {
    loadFromLocalStorage();
  }

  // 初始化存储
  initialize();

  return {
    // 状态
    accounts,
    currentAccountId,
    currentAccount,

    // 方法
    addAccount,
    updateAccount,
    removeAccount,
    setCurrentAccount,
    getAllAccounts,
  };
});
